<template>
  <div class="chat-container">
    <!-- 左侧对话列表 -->
    <div class="conversation-list">
      <div class="list-header">
        <h3>对话列表</h3>
        <button @click="createNewConversation" class="new-chat-btn">+ 新对话</button>
      </div>
      <ul>
        <li
            v-for="(conversation, index) in conversations"
            :key="conversation.id"
            :class="{ active: currentConversationId === conversation.id }"
            @click="switchConversation(conversation.id)"
        >
          <input
              v-if="editingTitleId === conversation.id"
              v-model="conversation.title"
              @blur="saveConversationTitle(conversation)"
              @keyup.enter="saveConversationTitle(conversation)"
              @keyup.esc="cancelEditTitle"
              class="title-input"
              ref="titleInput"
          />
          <span v-else @dblclick="editConversationTitle(conversation)">
            {{ conversation.title || `对话 ${index + 1}` }}
          </span>
          <span class="delete-btn" @click.stop="deleteConversation(conversation.id)">×</span>
        </li>
      </ul>
    </div>

    <!-- 右侧聊天区域 -->
    <div class="chat-area">
      <div class="chat-messages" ref="messagesContainer">
        <div v-if="loading" class="loading-indicator">
          <div class="loader"></div>
        </div>
        <div
            v-for="(message, index) in currentConversation.messages"
            :key="message.id"
            :class="['message', message.sender]"
        >
          <div class="message-content">
            <div v-if="editingMessageId === message.id" class="edit-message">
              <textarea
                  v-model="editingMessageText"
                  @blur="saveMessageEdit(message)"
                  @keyup.enter.exact="saveMessageEdit(message)"
                  @keyup.esc="cancelEditMessage"
                  ref="messageInput"
              ></textarea>
              <div class="edit-buttons">
                <button @click="saveMessageEdit(message)" class="save-btn">保存</button>
                <button @click="cancelEditMessage" class="cancel-btn">取消</button>
              </div>
            </div>
            <div v-else class="message-text" @dblclick="editMessage(message)">
              {{ message.text }}
            </div>
            <div class="message-time">{{ formatTime(message.timestamp) }}</div>
            <div v-if="message.edited" class="edited-label">已编辑</div>
          </div>
        </div>
      </div>
      <div class="chat-input">
        <textarea
            v-model="inputMessage.message"
            @keydown.enter.exact.prevent="sendMessage"
            placeholder="输入消息..."
            rows="1"
            ref="textarea"
        ></textarea>
        <button @click="sendMessage" :disabled="!inputMessage.message.trim() || loading">
          {{ loading ? '发送中...' : '发送' }}
        </button>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'ChatBot',
  data() {
    return {
      conversations: [],
      currentConversationId: null,
      inputMessage: {
        message: '',
        sessionId: null, // 用于多轮对话的会话ID
      },
      loading: false,
      editingTitleId: null,
      editingMessageId: null,
      editingMessageText: ''
    };
  },
  created() {
    this.loadConversations();
    if (this.conversations.length === 0) {
      this.createNewConversation();
    }
  },
  computed: {
    currentConversation() {
      return this.conversations.find(c => c.id === this.currentConversationId) || {};
    }
  },
  methods: {
    // 生成唯一ID
    generateId() {
      return Date.now().toString(36) + Math.random().toString(36).substr(2);
    },

    // 从本地存储加载对话
    loadConversations() {
      const saved = localStorage.getItem('chat-conversations');
      if (saved) {
        this.conversations = JSON.parse(saved);
        if (this.conversations.length > 0) {
          this.currentConversationId = this.conversations[0].id;
          // 初始化当前对话的sessionId
          this.inputMessage.sessionId = this.currentConversation.sessionId || this.generateId();
        }
      }
    },

    // 保存对话到本地存储
    saveConversations() {
      localStorage.setItem('chat-conversations', JSON.stringify(this.conversations));
    },

    // 创建新对话
    createNewConversation() {
      const sessionId = this.generateId();
      const newConversation = {
        id: this.generateId(),
        sessionId: sessionId, // 为对话分配sessionId
        title: `新对话 ${this.conversations.length + 1}`,
        messages: [
          {
            id: this.generateId(),
            text: '你好！我是AI助手，有什么可以帮您的吗？',
            sender: 'bot',
            timestamp: new Date(),
            edited: false
          }
        ]
      };
      this.conversations.unshift(newConversation);
      this.currentConversationId = newConversation.id;
      this.inputMessage = {
        message: '',
        sessionId: sessionId // 设置当前sessionId
      };
      this.saveConversations();

      this.$nextTick(() => {
        this.scrollToBottom();
      });
    },

    // 切换对话
    switchConversation(id) {
      const conversation = this.conversations.find(c => c.id === id);
      if (conversation) {
        this.currentConversationId = id;
        this.inputMessage.sessionId = conversation.sessionId || this.generateId();
        this.$nextTick(() => {
          this.scrollToBottom();
        });
      }
    },

    // 删除对话
    deleteConversation(id) {
      const index = this.conversations.findIndex(c => c.id === id);
      if (index !== -1) {
        this.conversations.splice(index, 1);
        if (this.currentConversationId === id) {
          this.currentConversationId = this.conversations[0]?.id;
          this.inputMessage.sessionId = this.conversations[0]?.sessionId || this.generateId();
        }
        this.saveConversations();
      }
    },

    // 编辑对话标题
    editConversationTitle(conversation) {
      this.editingTitleId = conversation.id;
      this.$nextTick(() => {
        this.$refs.titleInput[0]?.focus();
      });
    },
    // 编辑消息
    editMessage(message) {
      if (message.sender === 'user') {
        this.editingMessageId = message.id;
        this.editingMessageText = message.text;
        this.$nextTick(() => {
          this.$refs.messageInput[0]?.focus();
        });
      }
    },
    // 保存对话标题
    saveConversationTitle(conversation) {
      this.editingTitleId = null;
      this.saveConversations();
    },

    // 取消编辑标题
    cancelEditTitle() {
      this.editingTitleId = null;
    },
    // 保存消息编辑
    saveMessageEdit(message) {
      message.text = this.editingMessageText;
      message.edited = true;
      message.timestamp = new Date();
      this.editingMessageId = null;
      this.saveConversations();
    },

    // 取消编辑消息
    cancelEditMessage() {
      this.editingMessageId = null;
    },

    // 发送消息
    async sendMessage() {
      const message = this.inputMessage.message.trim();
      if (!message || this.loading) return;
      // 创建用户消息对象
      const userMessage = {
        id: this.generateId(),
        text: message,
        sender: 'user',
        timestamp: new Date(),
        edited: false
      };
      // 添加到当前对话
      this.currentConversation.messages.push(userMessage);
      // 如果是第一条用户消息，更新对话标题
      if (this.currentConversation.messages.filter(m => m.sender === 'user').length === 1) {
        this.currentConversation.title = message.slice(0, 20) + (message.length > 20 ? '...' : '');
      }
      const response = await axios.post('/api/chat/conversation', this.inputMessage
      );
      // 创建机器人回复消息
      const botMessage = {
        id: this.generateId(),
        text: response.data.response,
        sender: 'bot',
        timestamp: new Date(),
        edited: false
      };
      // 清空输入框但保留sessionId
      this.inputMessage.message = '';
      this.saveConversations();

      this.$nextTick(() => {
        this.scrollToBottom();
        this.adjustTextareaHeight();
      });

      this.loading = true;

        this.currentConversation.messages.push(botMessage);
        this.saveConversations();
        this.loading = false;
        this.$nextTick(() => {
          this.scrollToBottom();
        });
    },

    // 获取当前对话的历史消息（用于多轮对话上下文）
    getConversationHistory() {
      return this.currentConversation.messages
          .filter(msg => msg.sender === 'user' || msg.sender === 'bot')
          .map(msg => ({
            role: msg.sender === 'user' ? 'user' : 'assistant',
            content: msg.text
          }));
    },

    // 格式化时间
    formatTime(timestamp) {
      if (!timestamp) return '';
      const date = new Date(timestamp);
      return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
    },

    // 滚动到底部
    scrollToBottom() {
      const container = this.$refs.messagesContainer;
      if (container) {
        container.scrollTop = container.scrollHeight;
      }
    },

    // 调整输入框高度
    adjustTextareaHeight() {
      const textarea = this.$refs.textarea;
      if (textarea) {
        textarea.style.height = 'auto';
        textarea.style.height = `${Math.min(textarea.scrollHeight, 150)}px`;
      }
    }
  },
  mounted() {
    this.scrollToBottom();
    this.adjustTextareaHeight();
  },
  watch: {
    'inputMessage.message'() {
      this.$nextTick(() => {
        this.adjustTextareaHeight();
      });
    },
    currentConversationId(newVal) {
      if (newVal) {
        const conversation = this.conversations.find(c => c.id === newVal);
        if (conversation) {
          this.inputMessage.sessionId = conversation.sessionId || this.generateId();
        }
      }
    }
  }
};
</script>

<style scoped>
/* 样式部分与之前相同，保持不变 */
.chat-container {
  display: flex;
  height: 100vh;
  font-family: 'Arial', sans-serif;
}

.conversation-list {
  width: 250px;
  background-color: #f5f5f5;
  border-right: 1px solid #ddd;
  display: flex;
  flex-direction: column;
  overflow-y: auto;
}

.list-header {
  padding: 15px;
  border-bottom: 1px solid #ddd;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.list-header h3 {
  margin: 0;
  font-size: 16px;
}

.new-chat-btn {
  background-color: #4CAF50;
  color: white;
  border: none;
  padding: 5px 10px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
}

.new-chat-btn:hover {
  background-color: #45a049;
}

.conversation-list ul {
  list-style: none;
  padding: 0;
  margin: 0;
  flex-grow: 1;
}

.conversation-list li {
  padding: 12px 15px;
  border-bottom: 1px solid #eee;
  cursor: pointer;
  position: relative;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.conversation-list li:hover {
  background-color: #e9e9e9;
}

.conversation-list li.active {
  background-color: #e0e0e9;
  font-weight: bold;
}

.title-input {
  width: calc(100% - 20px);
  border: 1px solid #ddd;
  border-radius: 4px;
  padding: 2px 5px;
  font-size: inherit;
  font-family: inherit;
}

.delete-btn {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  color: #999;
  font-size: 18px;
  display: none;
}

.conversation-list li:hover .delete-btn {
  display: block;
}

.delete-btn:hover {
  color: #f44336;
}

.chat-area {
  flex-grow: 1;
  display: flex;
  flex-direction: column;
  background-color: #fff;
}

.chat-messages {
  flex-grow: 1;
  padding: 20px;
  overflow-y: auto;
  background-color: #f9f9f9;
  position: relative;
}

.loading-indicator {
  position: sticky;
  top: 10px;
  display: flex;
  justify-content: center;
  z-index: 10;
}

.loader {
  border: 3px solid #f3f3f3;
  border-top: 3px solid #4CAF50;
  border-radius: 50%;
  width: 30px;
  height: 30px;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.message {
  display: flex;
  margin-bottom: 15px;
}

.message.user {
  justify-content: flex-end;
}

.message.bot {
  justify-content: flex-start;
}

.message-content {
  max-width: 70%;
  padding: 10px 15px;
  border-radius: 18px;
  position: relative;
}

.message.user .message-content {
  background-color: #dcf8c6;
  margin-left: 30%;
}

.message.bot .message-content {
  background-color: #fff;
  border: 1px solid #ddd;
  margin-right: 30%;
}

.message-text {
  word-wrap: break-word;
  white-space: pre-wrap;
}

.message-text:hover {
  background-color: rgba(0, 0, 0, 0.03);
}

.edit-message {
  display: flex;
  flex-direction: column;
}

.edit-message textarea {
  width: 100%;
  min-height: 60px;
  border: 1px solid #ddd;
  border-radius: 8px;
  padding: 8px;
  font-family: inherit;
  resize: vertical;
}

.edit-buttons {
  display: flex;
  justify-content: flex-end;
  margin-top: 5px;
}

.edit-buttons button {
  margin-left: 5px;
  padding: 3px 8px;
  font-size: 12px;
  border-radius: 4px;
  cursor: pointer;
}

.save-btn {
  background-color: #4CAF50;
  color: white;
  border: none;
}

.cancel-btn {
  background-color: #f44336;
  color: white;
  border: none;
}

.message-time {
  font-size: 11px;
  color: #999;
  text-align: right;
  margin-top: 5px;
}

.edited-label {
  font-size: 10px;
  color: #999;
  text-align: right;
  font-style: italic;
}

.chat-input {
  padding: 15px;
  border-top: 1px solid #ddd;
  background-color: #fff;
  display: flex;
  align-items: flex-end;
}

.chat-input textarea {
  flex-grow: 1;
  border: 1px solid #ddd;
  border-radius: 20px;
  padding: 10px 15px;
  resize: none;
  max-height: 150px;
  outline: none;
  font-family: inherit;
  font-size: 14px;
}

.chat-input textarea:focus {
  border-color: #4CAF50;
}

.chat-input button {
  margin-left: 10px;
  padding: 10px 20px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 20px;
  cursor: pointer;
}

.chat-input button:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

.chat-input button:hover:not(:disabled) {
  background-color: #45a049;
}
</style>